import CryptoJS from 'crypto-js';

export class WXBizDataCrypt {
  private appId: string;
  private sessionKey: string;

  constructor(appId: string, sessionKey: string) {
    this.appId = appId;
    this.sessionKey = sessionKey;
  }

  decryptData(encryptedData: string, iv: string) {
    // base64 decode
    const sessionKey = CryptoJS.enc.Base64.parse(this.sessionKey);
    const encryptedDataBuffer = CryptoJS.enc.Base64.parse(encryptedData);
    const ivBuffer = CryptoJS.enc.Base64.parse(iv);

    try {
      // 解密
      const cipherParams = CryptoJS.lib.CipherParams.create({
        ciphertext: encryptedDataBuffer
      });
      const decipher = CryptoJS.AES.decrypt(cipherParams, sessionKey, {
        iv: ivBuffer,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });

      const decoded = decipher.toString(CryptoJS.enc.Utf8);
      const decodedData = JSON.parse(decoded);

      if (decodedData.watermark.appid !== this.appId) {
        throw new Error('Invalid appId');
      }

      return decodedData;
    } catch (err) {
      throw new Error('Decrypt failed');
    }
  }
}
